package top.heue.utils.base.helper.item

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import top.heue.utils.base.util.view.ScreenUtil.toPx

/** 自定义分割间隔，解决了中间item边距叠加的问题，单位dp，默认1列*/
class ItemDecoration(
    private val marginLeft: Int,
    private val marginRight: Int,
    private val marginTop: Int,
    private val marginBottom: Int,
    private val columns: Int = 1
) : RecyclerView.ItemDecoration() {

    constructor(margin: Int, columns: Int = 1) : this(
        margin,
        margin,
        margin,
        margin,
        columns
    )

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val context = parent.context
        //当前项在屏幕上总的项相对位置
        val pos = parent.getChildAdapterPosition(view)
        //当前项所在列
        val posLine = pos % columns
        var isTop = false
        var isLeft = false
        //var isRight = false
        if (posLine == 0) isLeft = true
        //计算了取余后依然相等说明就是第一行，即最顶
        if (posLine == pos) isTop = true
        //if (posLine == columns - 1) isRight = true
        outRect.left = if (isLeft) dp2px(context, marginLeft) else 0
        outRect.right = dp2px(context, marginRight)
        outRect.top = if (isTop) dp2px(context, marginTop) else 0
        outRect.bottom = dp2px(context, marginBottom)
    }

    private fun dp2px(context: Context, value: Int): Int = value.toPx(context).toInt()
}